"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.startAndWritePid = exports.writePid = exports.readPid = exports.pidFilepath = void 0;
const tslib_1 = require("tslib");
const crypto_1 = require("crypto");
const path = tslib_1.__importStar(require("path"));
const fs_1 = require("fs");
const utils_1 = require("./utils");
/**
 * 获取 .pid 文件路径
 */
async function pidFilepath() {
    return path.join(await utils_1.tempDir(), '.pid');
}
exports.pidFilepath = pidFilepath;
/**
 * 读取 .pid 文件
 */
async function readPid() {
    const pidFile = await pidFilepath();
    const content = await utils_1.readfile(pidFile);
    return content ? JSON.parse(content) : [];
}
exports.readPid = readPid;
/**
 * 写入 .pid 文件
 */
async function writePid(data) {
    await fs_1.promises.writeFile(await pidFilepath(), JSON.stringify(data, null, 2), 'utf-8');
}
exports.writePid = writePid;
/**
 * 启动时检查id 并写入 .pid 文件
 */
async function startAndWritePid(data) {
    const id = data.id = data.id || crypto_1.createHash('md5').update(new Date().toString()).digest('hex').slice(0, 6);
    const list = await readPid();
    if (list.some(item => item.id === id)) {
        console.error(`${id} 已存在，请更换 id 或停止运行${id}（tagup stop ${id}）`);
        process.exit();
    }
    else {
        list.push(data);
        await writePid(list);
    }
}
exports.startAndWritePid = startAndWritePid;
